#include <QPainter>
#include <QBrush>
#include "StateBar.h"
#include "DataCenter.h"

StateBar::StateBar(QWidget *parent) : QWidget(parent)
{
    refresh();
    connect(&DataCenter::instance(), &DataCenter::extendedDataChanged, this, &StateBar::refresh);
}

void StateBar::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    QBrush brush;
    int itemWidth = width() / 7;
    for (int i = 1; i <= 6; i++)
    {
        switch (states[i])
        {
        case UnKnow:
            brush = Qt::white;
            break;
        case Empty:
            brush = Qt::green;
            break;
        case Little:
            brush = Qt::yellow;
            break;
        case Busy:
            brush = Qt::red;
            break;
        case FestivalEmpty:
            brush = QColor("#9933FA");
            break;
        case FestivalNotEmpty:
            brush = QColor("#DA70D6");
            break;
        }
        if (i != 6)
            painter.fillRect(QRect(itemWidth * i - 3, 0, itemWidth + 1, height()), brush);
        else
            painter.fillRect(QRect(itemWidth * i - 3, 0, itemWidth - 2, height()), brush);
    }

}

void StateBar::refresh()
{
    for (auto &s : states)
        s = Empty;

    QMap<QDate, QVector<ScheduleDataInfo> > info;
    DataCenter::instance().getJobs(QDate::currentDate().addDays(1), QDate::currentDate().addDays(6), info);
    QMapIterator<QDate, QVector<ScheduleDataInfo>> i(info);
    while (i.hasNext())
    {
        i.next();
        int index = int(QDate::currentDate().daysTo(i.key()));
        assert(0 <= index && index < STATE_COUNT);
        bool isFestival = false;
        int count = i.value().count();
        for (const ScheduleDataInfo& item : i.value())
        {
            if (item.getType() == 4)
                isFestival = true;
            else if (DataCenter::instance().getExtendedData(item).isChecked)
                count -= 1;
        }
        if (isFestival)
        {
            if (count == 1)
                states[index] = FestivalEmpty;
            else if (count > 1)
                states[index] = FestivalNotEmpty;
            else
                states[index] = UnKnow;
        }
        else
        {
            if (count == 0)
                states[index] = Empty;
            else if (1 <= count && count <= 3)
                states[index] = Little;
            else if (count > 3)
                states[index] = Busy;
            else
                states[index] = UnKnow;
        }

    }
    update();
}
